package server;

import client.InvokerBean;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 创建监听,如果有需要,可以改成线程池
 */
public class Listener extends  Thread {
    private RPCServer rpcServer ;
    public Listener(RPCServer rpcServer) {
        this.rpcServer = rpcServer;
    }
    public void run(){
        ServerSocket server = null;
        try {
            server = new ServerSocket(rpcServer.getPort());
            System.out.println("server start..");
            while (rpcServer.isRun()) {
                Socket socket = server.accept();
                //解析流
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                InvokerBean in = (InvokerBean) ois.readObject();
                String serviceName = in.getServiceName();
                String methodName = in.getMethod().getMethodname();
                Class<?>[] parameterType = in.getMethod().getParameterTypes();
                Object[] parameters = in.getParameters();
                System.out.println("invoking... serviceName = " + serviceName + ". methodName = " + methodName);;

                //注册的服务列表中,获取服务, 使用反射调用
                Object service = rpcServer.getServiceEngine().get(serviceName);
                if(server ==null){
                    System.err.println("service not found");
                }else{
                    Class<?> InterfaceClass = Class.forName(serviceName);
                    Method method = InterfaceClass.getMethod(methodName, parameterType);
                    Object  result = method.invoke(service,parameters);
                    in.setResult(result);
                }
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                oos.writeObject(in);
                oos.flush();

                socket.close();
                System.out.println("invoking over");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Server stoped");
    }
}
